import { useControlController, useNamespace } from '@ibiz-template/vue3-util';
import { computed, defineComponent, PropType } from 'vue';
import { ISearchBar } from '@ibiz/model-core';
import { SearchBarController } from './search-bar.controller';
import './search-bar.scss';

export const SearchBarControl = defineComponent({
  name: 'IBizSearchBarControl',
  props: {
    modelData: {
      type: Object as PropType<ISearchBar>,
      required: true,
    },
    context: { type: Object as PropType<IContext>, required: true },
    params: { type: Object as PropType<IParams>, default: () => ({}) },
  },
  setup() {
    const c = useControlController(
      (...args) => new SearchBarController(...args),
    );
    const ns = useNamespace(`control-${c.model.controlType!.toLowerCase()}`);

    const onSearch = (): void => {
      c.handleSearch();
    };

    const onKeydown = (e: KeyboardEvent): void => {
      if (e.code === 'Enter') {
        c.handleSearch();
      }
    };

    const cssVars = computed(() => {
      if (c.model.quickSearchWidth) {
        return ns.cssVarBlock({
          'quick-search-width': `${c.model.quickSearchWidth}px`,
        });
      }
      return {};
    });

    return { c, ns, onSearch, onKeydown, cssVars };
  },
  render() {
    return (
      <iBizControlBase
        controller={this.c}
        class={[this.ns.b()]}
        style={this.cssVars}
      >
        {this.c.model.enableQuickSearch && (
          <el-input
            v-model={this.c.state.query}
            class={this.ns.b('quick-search')}
            placeholder={this.c.placeHolder}
            onKeydown={this.onKeydown}
          >
            {{
              append: () => {
                return (
                  <el-button
                    type='primary'
                    icon={
                      <ion-icon
                        class={this.ns.e('search-icon')}
                        name='search'
                      />
                    }
                    onClick={this.onSearch}
                  />
                );
              },
            }}
          </el-input>
        )}
      </iBizControlBase>
    );
  },
});
